package com.workManager.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.workManager.exception.BusinessException;
import com.workManager.mapper.TbSalaryMapper;
import com.workManager.mapper.TdUserMapper;
import com.workManager.pojo.TbSalary;
import com.workManager.pojo.TdUser;
import com.workManager.util.ExcelReadUtil;
import com.workManager.vo.ProjectSalaryTempVo;
import com.workManager.vo.ProjectSalaryVo;
import com.workManager.vo.SalarySpreadVo;
import com.workManager.vo.SalaryVo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by worso on 2017/3/21 0021.
 */
@Service
public class SalaryServiceImpl implements SalaryService {

    private static Logger logger = Logger.getLogger(SalaryServiceImpl.class);

    @Autowired
    private TdUserMapper userMapper;

    @Autowired
    private TbSalaryMapper salaryMapper;

    public PageInfo<SalaryVo> queryDetails(Map<String, Object> queryParam) {
        int pageno = !queryParam.containsKey("pagenum")||queryParam.get("pagenum")==null?1:Integer.parseInt(queryParam.get("pagenum").toString());
        int pagesize = !queryParam.containsKey("pagesize")||queryParam.get("pagesize")==null?10:Integer.parseInt(queryParam.get("pagesize").toString());
        PageHelper.startPage(pageno,pagesize);
        List<SalaryVo> salaryVoList = salaryMapper.queryDetails(queryParam);
        PageInfo<SalaryVo> pageInfo = new PageInfo<SalaryVo>(salaryVoList);
        return pageInfo;
    }

    @Transactional
    public void uploadExcel(String name , MultipartFile file) throws  Exception{

        //CurrentUserVO userVO = WebUtil.getCurrentUserVO();
        List<String[]> fileData = ExcelReadUtil.excelToList(name,file.getInputStream());

        String[] tableHead = fileData.get(0);
        String[] headTitle = {"年份","月份","部门","姓名","工资","社保","住房公积金","商保","总计"};
        for (int i=0;i<headTitle.length;i++){
            String  headItem = tableHead[i];
            if(!headItem.equals(headTitle[i])){
                throw  new BusinessException("表格格式不正确！请检查表格格式重新上传。(行：1，列："+(i+1)+")");
            }
        }

        //匹配金额
        String reg = "^-?[0-9]{1,8}(.[0-9]{1,2})?$";

        for(int i=1;i<fileData.size();i++){
            String[] rowData = fileData.get(i);

            //检查是否空行
            if(ExcelReadUtil.isBlankRow(rowData)){
                continue;
            }

            String salYear = rowData[0];
            String salMonth = rowData[1];
            String userName = rowData[3];
            String wages = rowData[4];
            String socialInsurance = rowData[5];
            String housingFund = rowData[6];
            String commercialInsurance = rowData[7];
            String totalAmount = rowData[8];

            if(!wages.matches(reg) ){
                throw new BusinessException("金额请精确到小数点后2位，整数位不大于8位(行："+i+"，列：1)");
            }else if(!socialInsurance.matches(reg)){
                throw new BusinessException("金额请精确到小数点后2位，整数位不大于8位(行："+i+"，列：6)");
            }else if(!housingFund.matches(reg)){
                throw new BusinessException("金额请精确到小数点后2位，整数位不大于8位(行："+i+"，列：7)");
            }else if(!commercialInsurance.matches(reg)){
                throw new BusinessException("金额请精确到小数点后2位，整数位不大于8位(行："+i+"，列：8)");
            }else if(!totalAmount.matches(reg)){
                throw new BusinessException("金额请精确到小数点后2位，整数位不大于8位(行："+i+"，列：9)");
            }else if(Integer.parseInt(wages)+Integer.parseInt(socialInsurance)+Integer.parseInt(housingFund)+Integer.parseInt(commercialInsurance)!=Integer.parseInt(totalAmount)){
                throw new BusinessException("["+salYear+"-"+salMonth+"]"+"["+userName+"]："+"合计金额不正确(行："+i+"，列：9)");
            }




            TbSalary salary = new TbSalary();
            TdUser user = userMapper.queryUserByName(userName);

            if(user==null){
                throw  new BusinessException("姓名："+userName+" 不存在！请检查数据重新上传。(行："+i+"，列：4)");
            }

            salary.setSalMonth(salMonth.trim().length() <2 ? salYear.trim() + "-0" + salMonth.trim() : salYear.trim() + "-" + salMonth.trim());
            salary.setUserId(user.getUserId());
            salary.setWages(new BigDecimal(wages));
            salary.setSocialInsurance(new BigDecimal(socialInsurance));
            salary.setHousingFund(new BigDecimal(housingFund));
            salary.setCommercialInsurance(new BigDecimal(commercialInsurance));
            salary.setTotalAmount(new BigDecimal(totalAmount));
            salary.setCreateDate(new Date());
            salary.setIsValid(true);

            TbSalary tbSalary = salaryMapper.selectByUserWithMonth(salary.getUserId(),salary.getSalMonth());
            if(tbSalary ==null){
                salaryMapper.insert(salary);
            }else{
                logger.info("更新记录前("+tbSalary.getSalaryId()+")："+"年份("+ salYear+"),月份("+salMonth+"),姓名("+userName
                        +"),工资("+tbSalary.getWages()+ "),社保("+tbSalary.getSocialInsurance()+"),住房公积金("+tbSalary.getHousingFund()
                        +"),商保("+tbSalary.getCommercialInsurance()+"),总计("+tbSalary.getTotalAmount()+")");

                salary.setSalaryId(tbSalary.getSalaryId());
                salaryMapper.updateByPrimaryKey(salary);
                logger.info("更新记录前("+salary.getSalaryId()+")："+"年份("+salYear+"),月份("+salMonth+"),姓名("+userName
                        +"),工资("+wages+ "),社保("+socialInsurance+"),住房公积金("+housingFund
                        +"),商保("+commercialInsurance+"),总计("+totalAmount+")");
            }

        }
    }

    public PageInfo<ProjectSalaryVo> countByProjectInMonth(Map<String, Object> queryParam) {
        int pageno = !queryParam.containsKey("pagenum")||queryParam.get("pagenum")==null?1:Integer.parseInt(queryParam.get("pagenum").toString());
        int pagesize = !queryParam.containsKey("pagesize")||queryParam.get("pagesize")==null?10:Integer.parseInt(queryParam.get("pagesize").toString());
        PageHelper.startPage(pageno,pagesize);
        List<ProjectSalaryVo> projectSalaryVoList = salaryMapper.countByProjectInMonth(queryParam);
        PageInfo<ProjectSalaryVo> pageInfo = new PageInfo<ProjectSalaryVo>(projectSalaryVoList);
        return pageInfo;
    }

    public List<ProjectSalaryTempVo> countByProjectInMonthTemp(Map<String, Object> map) {

        List<ProjectSalaryTempVo> projectSalaryVoList = salaryMapper.countByProjectInMonthTemp(map);

        return projectSalaryVoList;

    }

    public List<SalarySpreadVo> salarySpreadInMonth(String month, String projectId, String userId){
        return salaryMapper.salarySpreadInMonth( month, projectId, userId);
    }

}
